package com.quectel.core.module.devicepatrol.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.constant.core.devicepatrol.DevicePatrolEventReportConstants;
import com.quectel.constant.core.devicepatrol.DevicePatrolTaskConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.ex.devicepatrol.PatrolReportException;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.devicepatrol.dao.DevicePatrolEventReportDao;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolEventReportDto;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolTaskDto;
import com.quectel.core.module.devicepatrol.entity.DevicePatrolEventReportEntity;
import com.quectel.core.module.devicepatrol.service.DevicePatrolEventReportService;
import com.quectel.core.module.devicepatrol.service.DevicePatrolTaskService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.core.module.workorder.service.WorkOrderService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:06
 */
@DubboService
public class DevicePatrolEventReportServiceImpl extends ServiceImpl<DevicePatrolEventReportDao, DevicePatrolEventReportEntity> implements DevicePatrolEventReportService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DevicePatrolEventReportServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> DEVICE_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "DEVICE_PATROL_EVENT_REPORT_CACHE_BY_ID:%d", id);

    @Autowired
    private DevicePatrolEventReportDao devicePatrolEventReportDao;
    @Autowired
    private VillageService villageService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private DevicePatrolTaskService devicePatrolTaskService;


    @Override
    public void saveBatch(List<DevicePatrolEventReportDto> dtos) {
        List<DevicePatrolEventReportEntity> list = dtos.stream().map(
                dto -> {
                    dto.setId(Snowflake.nextId());
                    return CopyUtils.copyObj(dto, DevicePatrolEventReportEntity.class);
                }
        ).collect(Collectors.toList());
        super.saveBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void report(DevicePatrolEventReportDto reportDto, DevicePatrolTaskDto taskDto) {

        updateById(reportDto);

        //重新查询数据库中的task
        DevicePatrolTaskDto dbTaskDto = devicePatrolTaskService.selectById(reportDto.getTaskId());
        //和数据库保持一致
        if (dbTaskDto == null || !dbTaskDto.getExecStatus().equals(taskDto.getExecStatus()) || !dbTaskDto.getExecCount().equals(taskDto.getExecCount())) {
            throw new PatrolReportException(SystemConstants.ILLEGAL_MSG);
        }
        //首次上报修改状态
        if (DevicePatrolTaskConstants.TasksStatusEnum.STATUS_UNEXECUTED.getStatus().equals(taskDto.getExecStatus())) {
            taskDto.setExecStatus(DevicePatrolTaskConstants.TasksStatusEnum.STATUS_EXECUTING.getStatus());
            taskDto.setExecCount(0);
        }
        //更新执行数量
        Integer execCount = taskDto.getExecCount();
        taskDto.setExecCount(++execCount);

        //更新 routeExecTotalStatus
        if (DevicePatrolEventReportConstants.ReportStatusEnum.STATUS_ABNORMAL.getStatus().equals(reportDto.getStatus()) ||
                DevicePatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus().equals(reportDto.getStatus())
        ) {
            Set<Byte> routeExecTotalStatusSet = new HashSet<>();
            if (StringUtils.isNotBlank(taskDto.getRouteExecTotalStatus())) {
                routeExecTotalStatusSet = JacksonUtils.parse(taskDto.getRouteExecTotalStatus(), new TypeReference<Set<Byte>>() {
                });
            }
            routeExecTotalStatusSet.add(reportDto.getStatus());
            taskDto.setRouteExecTotalStatus(JacksonUtils.toJsonString(routeExecTotalStatusSet));
        }

        //如果上报数量和路线数量一直,则任务已完成
        if (taskDto.getRouteCount().equals(execCount)) {
            taskDto.setExecStatus(DevicePatrolTaskConstants.TasksStatusEnum.STATUS_EXECUTED.getStatus());
            taskDto.setCompleteTime(reportDto.getCompleteTime());
        }
        devicePatrolTaskService.updateById(taskDto);
    }

    @Override
    public DevicePatrolEventReportDto selectByTaskIdAndDeviceId(Long taskId, Long deviceId) {
        DevicePatrolEventReportEntity entity = devicePatrolEventReportDao.selectOne(new LambdaQueryWrapper<DevicePatrolEventReportEntity>()
                .eq(DevicePatrolEventReportEntity::getTaskId, taskId)
                .eq(DevicePatrolEventReportEntity::getDeviceId, deviceId));
        return paddingField(CopyUtils.copyObj(entity, DevicePatrolEventReportDto.class));
    }

    @Override
    public List<DevicePatrolEventReportDto> selectByDevicePatrolTaskId(Long taskId) {
        List<DevicePatrolEventReportEntity> entities = devicePatrolEventReportDao.selectList(new LambdaQueryWrapper<DevicePatrolEventReportEntity>().eq(DevicePatrolEventReportEntity::getTaskId, taskId));
        List<DevicePatrolEventReportDto> result = CopyUtils.copyList(entities, DevicePatrolEventReportDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public DevicePatrolEventReportDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                DEVICE_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public DevicePatrolEventReportDto selectById(Long id) {
        DevicePatrolEventReportEntity entity = devicePatrolEventReportDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, DevicePatrolEventReportDto.class));
    }

    @Override
    public List<DevicePatrolEventReportDto> queryList(Map<String, Object> params) {
        List<DevicePatrolEventReportEntity> list = devicePatrolEventReportDao.queryList(params);
        List<DevicePatrolEventReportDto> result = CopyUtils.copyList(list, DevicePatrolEventReportDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private DevicePatrolEventReportDto paddingField(DevicePatrolEventReportDto dto) {
        if (dto != null) {

            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            if (villageDto != null) {
                dto.setVillageName(villageDto.getName());
            }

            DeviceDto deviceDto = deviceService.selectById(dto.getDeviceId());

            if (deviceDto != null) {
                dto.setDeviceName(deviceDto.getName());
                dto.setImei(deviceDto.getImei());
                dto.setInstallAddress(deviceDto.getInstallAddress());
            }

            if (DevicePatrolEventReportConstants.AssignWorkOrderStatusEnum.ASSIGN_WORK_ORDER.getStatus().equals(dto.getAssignWorkOrder())) {
                dto.setWorkOrderDto(workOrderService.selectById(dto.getWorkOrderId()));
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return devicePatrolEventReportDao.queryTotal(params);
    }

    @Override
    public Long save(DevicePatrolEventReportDto dto) {
        DevicePatrolEventReportEntity entity = CopyUtils.copyObj(dto, DevicePatrolEventReportEntity.class);
        entity.setId(Snowflake.nextId());
        devicePatrolEventReportDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(DevicePatrolEventReportDto dto) {
        DevicePatrolEventReportEntity entity = CopyUtils.copyObj(dto, DevicePatrolEventReportEntity.class);
        devicePatrolEventReportDao.updateById(entity);
        CacheKit.invalidRedisCache(DEVICE_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(DevicePatrolEventReportDto dto) {
        DevicePatrolEventReportEntity entity = CopyUtils.copyObj(dto, DevicePatrolEventReportEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, devicePatrolEventReportDao);

        CacheKit.invalidRedisCache(DEVICE_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        devicePatrolEventReportDao.deleteById(id);

        CacheKit.invalidRedisCache(DEVICE_PATROL_EVENT_REPORT_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
